class CartsController < ApplicationController
  include CartsHelper

  before_filter :authenticate, :only => [:show, :checkout]

  def show
    @cart.user_id = current_user.id
    @cart.save!
  end

  def checkout
    @cart.update_attributes(params[:cart])
  end

  def final
    @cart.order_placed = 1
    @cart.save!

    pdf_path = OrderReport.new(:page_size => "A4").to_pdf_file(@cart, current_user)

    # Send confirmation mail
    ShopMailer.order_confirmation(current_user, @cart, pdf_path).deliver

    destroy_cart
    File.delete(pdf_path)
    redirect_to current_user
  end

  def bestellung

    @cart = Cart.find_by_id(params[:cart_id])
    output = OrderReport.new(:page_size => "A4").to_pdf_http(@cart, current_user)

    respond_to do |format|
      #format.pdf
      format.pdf do
        send_data output, :filename => "bestellung.pdf",
                          :type => :pdf
      end
    end
  end

  def add
    @item = @cart.add(params[:id])
    respond_to do |format|
      format.js
    end
  end

  def remove
    @item = @cart.remove(params[:id])
    respond_to do |format|
      format.js
    end
  end

  private
  def destroy_cart
    session[:cart_id] = nil
  end


end